package it.unibz.ti2.internetPizzeria.servlets;

import it.unibz.ti2.internetPizzeria.dao.DuplicatedLoginException;
import it.unibz.ti2.internetPizzeria.dao.UserDAO;
import it.unibz.ti2.internetPizzeria.entities.Customer;
import it.unibz.ti2.internetPizzeria.utils.ServletUtil;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Registering new customer's account
 */
public class NewCustomer extends HttpServlet {

	private static final long serialVersionUID = 8745613290632322846L;

	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		this.doPost(arg0, arg1);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserDAO dao = new UserDAO();
		boolean sthWrong = false;
		try {
			Customer customer = new Customer();
			customer.setLogin(request.getParameter("login"));
			customer.setPasswordHash(request.getParameter("password").hashCode());
			customer.setName(request.getParameter("name"));
			customer.setSurname(request.getParameter("surname"));
			customer.setStreetAndNumber(request.getParameter("streetAndNumber"));
			customer.setZipCode(request.getParameter("zipCode"));
			customer.setCity(request.getParameter("city"));
			customer.setCountry(request.getParameter("country"));
			customer.setTelephone(request.getParameter("telephone"));
						
			dao.openSession();			
			dao.addNewUser(customer);
			
		} catch (DuplicatedLoginException e) {
			request.setAttribute("duplicatedLogin", "Choose other login");
			sthWrong = true;		
		} finally{
			dao.closeSession();			
		}
		if (sthWrong){
			ServletUtil.redirect(request, response, "/newCustomer.jsp");
		}
		else{
			ServletUtil.redirect(request, response, "/login.jsp");
		}
	}
}
